package com.a918.controller;

import com.a918.dto.TableResponse;
import com.a918.entity.Orgmonth;
import com.a918.entity.Weight;
import com.a918.service.EvaluateService;
import com.a918.service.ImportDataService;
import com.a918.service.UserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class EvaluateController {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserController.class);
    private static final String APIKEY = "afe8547e16f7d693";

    private UserService userService;
    private EvaluateService evaluateService;
    private ImportDataService importDataService;

    @Autowired
    public EvaluateController(UserService userService,EvaluateService evaluateService,ImportDataService importDataService) {
        this.userService = userService;
        this.evaluateService=evaluateService;
        this.importDataService=importDataService;
    }

    @GetMapping("/evaluate")
    public String evaluate(Model model, HttpServletRequest request) throws ParseException {
        String type= request.getParameter("type");
        // 用于首页点击省份进入列表
        String shengfen = request.getParameter("shengfen");
        String field = request.getParameter("field");
        String order = request.getParameter("order");
        model.addAttribute("shengfen",shengfen);
        model.addAttribute("field",field);
        model.addAttribute("order",order);

        switch (type){
            case "orgList":
                return "back/memberlist_zonghe";
            case "orgListCollected":
                return "back/collected_memberlist";
            case "zonghe":
                // 设置三个时间选择器的默认值
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                // 当前日期&月份
                String now = df.format(System.currentTimeMillis());
                String yuefen = now.substring(0,7);

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.MONTH, -5);
                // 最近六个月
                String yuefenRange = new SimpleDateFormat("yyyy-MM").format(calendar.getTime()) + " - " + yuefen;

                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, -13);
                // 最近14天
                String date1 = df.format(calendar.getTime()) + " - " + now;

                model.addAttribute("yuefen", yuefen);
                model.addAttribute("yuefenRange", yuefenRange);
                model.addAttribute("date", date1);

                // 列表点击详情时获取编号
                String orgCode = request.getParameter("orgCode");
                String yuefen1 = request.getParameter("yuefen");
                if (orgCode == null || orgCode.equals("") || yuefen1 == null || yuefen1.equals("")) {
                    return "back/evaluate";
                }
                // 详情时，date设置为当月所有天
                calendar.setTime(df.parse(yuefen1+"-01"));
                calendar.add(Calendar.MONTH, -1);
                String yuefen2 = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
                model.addAttribute("yuefen",yuefen1);
                model.addAttribute("date",yuefen2+"-01" + " - " + yuefen2 + "-31");
                model.addAttribute("orgCode", orgCode);
                return "back/evaluate";
            case "workLength":
                return "back/evaluateWorkLength";
            case "yewuliang":
                return "back/evaluateYewuliang";
            case "shixiao":
                return "back/evaluateShixiao";
        }
        return "back/evaluate";
    }

    // 获取yuefen的orgmonth的最大最小值以及权重，复用
    public void getMinMaxAndWeight(Map<String,Object> result, String yuefen) {
        Map<String,Map<String,Float>> twoMaps;
        Map<String,Float> maxMap, minMap;
        Map<String, Object> max_min = evaluateService.getMinAndMaxZhibiao(yuefen);
        twoMaps = (Map<String, Map<String, Float>>) max_min.get("res");
        maxMap = twoMaps.get("max");
        minMap = twoMaps.get("min");
        result.put("max_averageAge",maxMap.get("AverageAge"));
        result.put("max_dailyMaxWaybillCount",maxMap.get("DailyMaxWaybillCount"));
        result.put("max_laborProductivity",maxMap.get("LaborProductivity"));
        result.put("max_avgDeliveryCountRate",maxMap.get("AvgDeliveryCountRate"));
        result.put("max_deliveryRate", maxMap.get("DeliveryRate"));
        result.put("max_workload", maxMap.get("Workload"));
        result.put("min_averageAge",minMap.get("AverageAge"));
        result.put("min_dailyMaxWaybillCount",minMap.get("DailyMaxWaybillCount"));
        result.put("min_laborProductivity",minMap.get("LaborProductivity"));
        result.put("min_avgDeliveryCountRate",minMap.get("AvgDeliveryCountRate"));
        result.put("min_deliveryRate", minMap.get("DeliveryRate"));
        result.put("min_workload", minMap.get("Workload"));

        Weight w = evaluateService.getByYuefen(yuefen);

        result.put("W_dailyMaxWaybillCount",w.getDailymaxwaybillcount());
        result.put("W_averageAge",w.getAverageage());
        result.put("W_waybillNoCount",w.getWaybillnocount());
        result.put("W_avgDeliveryCountRate",w.getAvgdeliverycountrate());
        result.put("W_deliveryRate", w.getDeliveryrate());
        result.put("W_workload", w.getWorkload());
    }

    @PostMapping("/get_evaluate")
    @ResponseBody
    public Map<String,Object> get_evaluate(@RequestParam String wangdian, HttpServletRequest request) throws ParseException {
        String type=request.getParameter("type");

        Map<String,Object> result=new HashMap<>();
        String yuefen;
        String date;
        String dateBgn;
        String dateEnd;
        switch (type) {
            case "zonghe":
                yuefen = request.getParameter("yuefen");

                Orgmonth orgmonth = evaluateService.getByNameAndYuefen(wangdian, yuefen);
                if (orgmonth == null) {
                    result.put("res", "fail");
                } else {
                    result.put("res", "success");
                    Orgmonth maxShangquanf = evaluateService.getMaxShangquanf(yuefen);
                    // List<Double> maxAttribute = evaluateService.getMaxAttribute();

                    result.put("orgmonth", orgmonth);
                    result.put("maxShangquanf",maxShangquanf);
                    // result.put("maxAttribute",maxAttribute);
                    getMinMaxAndWeight(result, yuefen);

                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    calendar.setTime(df.parse(yuefen+"-01"));
                    // calendar.add(Calendar.MONTH, -1);
                    String yuefen2 = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
                    result.put("date",yuefen2+"-01" + " - " + yuefen2 + "-31");
                }

                return result;
            case "workLength":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getWorkLengthByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;
            case "yewuliang":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getYewuliangByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;
            case "shixiao":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getShixiaoByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;
            case "shengchanlv":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getShengchanlvByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;
            case "deliveryCount":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getDeliveryCountByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;

            case "deliveryCountOfDay":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getDeliveryCountOfDayByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;
            case "deliveryCountRate":
                date = request.getParameter("date");
                dateBgn=date.substring(0,10);
                dateEnd=date.substring(13);
                result=evaluateService.getDeliveryCountRateByNameAndDateRange(wangdian, dateBgn, dateEnd);
                return result;

            case "shangquanf":
                try{
                    String yuefenRange=request.getParameter("yuefenRange");
                    String yuefenBgn=yuefenRange.substring(0,7);
                    String yuefenEnd=yuefenRange.substring(10);

                    result=evaluateService.getShangquanfByNameAndYuefenRange(wangdian,yuefenBgn,yuefenEnd);
                } catch (Exception e){
                    result=null;
                }
                return result;
        }
        return result;
    }

    @PostMapping("/advice")
    @ResponseBody
    public Map<String, String> advice(@RequestParam String wangdian, HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();
        String yuefen = request.getParameter("yuefen");
        Orgmonth orgmonth = evaluateService.getByNameAndYuefen(wangdian, yuefen);
        // 排名情况
        int[] nums = evaluateService.getOrgNumOfType(yuefen);
        int total = nums[0], numOfType;
        String type = orgmonth.getType();
        switch (type) {
            case "小规模":
                numOfType = nums[1];
                break;
            case "中规模":
                numOfType = nums[2];
                break;
            case "大规模":
                numOfType = nums[3];
                break;
            default:
                numOfType = nums[4];
                break;
        }

        double loadscore_yuzhi = evaluateService.getLoadScoreByYuefenAndLoadRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double staffscore_yuzhi = evaluateService.getStaffScoreByYuefenAndStaffRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double agescore_yuzhi = evaluateService.getAgeScoreByYuefenAndAgeRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double laborscore_yuzhi = evaluateService.getLaborScoreByYuefenAndLaborRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double dailyscore_yuzhi = evaluateService.getDailyScoreByYuefenAndDailyRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double maxscore_yuzhi = evaluateService.getMaxScoreByYuefenAndMaxRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);


        String rank = String.format("当前网点效率分数为%.2f,超过%.2f%%的网点,排名%d; 本月业务量为%d, 属于%s网点,超过%.2f%%的同类网点,同类网点中排名%d。",
                orgmonth.getShangquanf(), 100-100.0*orgmonth.getRank1()/total, orgmonth.getRank1(),
                orgmonth.getDeliveryCountMonth(), orgmonth.getType(), 100-100.0*orgmonth.getRank2()/numOfType,orgmonth.getRank2());

        String load_rank = String.format("当前网点工作负荷分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getLoadScore(),100-100.0*orgmonth.getLoadRank()/numOfType,loadscore_yuzhi);
        String staff_rank = String.format("当前网点人员利用率分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getStaffScore(),100-100.0*orgmonth.getStaffRank()/numOfType,staffscore_yuzhi);

        String age_rank = String.format("当前网点派送时效分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getAgeScore(),100-100.0*orgmonth.getAgeRank()/numOfType,agescore_yuzhi);
        String labor_rank = String.format("当前网点劳动生产率分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getLaborScore(),100-100.0*orgmonth.getLaborRank()/numOfType,laborscore_yuzhi);

        String daily_rank = String.format("当前网点当日派件率分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getDailyScore(),100-100.0*orgmonth.getDailyRank()/numOfType,dailyscore_yuzhi);
        String max_rank = String.format("当前网点最大派送能力分数为%.2f，超过%.2f%%同类网点，根据同类网点本月的运营情况，该指标%.2f分以上为良好，以下为较差。",
                orgmonth.getMaxScore(),100-100.0*orgmonth.getMaxRank()/numOfType,maxscore_yuzhi);

        // 较差指标
        List<String> weakIndex = new ArrayList<>();
        if (1.0 * orgmonth.getAgeRank() / numOfType > 0.6) {
            weakIndex.add("派送时效");
        }
        if (1.0 * orgmonth.getDailyRank() / numOfType > 0.6) {
            weakIndex.add("当日派件率");
        }
        if (1.0 * orgmonth.getLaborRank() / numOfType > 0.6) {
            weakIndex.add("劳动生产率");
        }
        if (1.0 * orgmonth.getMaxRank() / numOfType > 0.6) {
            weakIndex.add("最大派送能力");
        }
        if (1.0 * orgmonth.getStaffRank() / numOfType > 0.6) {
            weakIndex.add("人员利用率");
        }
        if (1.0 * orgmonth.getLoadRank() / numOfType > 0.6) {
            weakIndex.add("工作负荷");
        }
        int n = weakIndex.size();
        if (n > 0) {
            StringBuilder weak = new StringBuilder("当前网点");
            for (int i = 0; i < n; ++i) {
                weak.append(weakIndex.get(i));
                if (i != n-1) {
                    weak.append("、");
                }
            }
            weak.append("指标分数较差。");
            result.put("weak", weak.toString());

            // 改进建议
            Map<String, String> advices = new HashMap<>();
            advices.put("派送时效", "平均时效：网点当前平均派送时效较长，可以通过使用智能快递柜、启用代收点、驿站等方式缩短时效。");
            advices.put("当日派件率", "当日派件率：网点当前当日派件率较低，可以通过合理安排下车、派送时间，合理使用快递柜、驿站等方式提高当日派件率。");
            advices.put("劳动生产率", "劳动生产率：网点当前劳动生产率较低，可以通过与其他网点进行资源共享、重新规划区域等方式提高劳动生产率。");
            advices.put("最大派送能力", "最大派送能力：网点当前最大派送能力较低，可以通过与其他网点资源共享提升最大派送能力。");
            advices.put("人员利用率", "人员利用率：网点当前人员利用率较低，应尽量提升人员稳定性，减少人员流失。");
            advices.put("工作负荷", "工作负荷：网点当前人员工作负荷较高，可以通过增加快递员数量、重新规划区域等方式降低快递员工作负荷。");

            StringBuilder advice = new StringBuilder();
            for (int i = 0; i < n; ++i) {
                advice.append(advices.get(weakIndex.get(i)));
                if (i != n-1) {
                    advice.append("\n");
                }
            }
            result.put("advice", advice.toString());
        } else {
            result.put("advice", "当前各项指标表现良好，请继续努力！");
        }

        result.put("rank",rank);
        result.put("load_rank",load_rank);
        result.put("staff_rank",staff_rank);
        result.put("age_rank",age_rank);
        result.put("labor_rank",labor_rank);
        result.put("daily_rank",daily_rank);
        result.put("max_rank",max_rank);
        return result;
    }

    @PostMapping("/orgList")
    @ResponseBody
    public Object orgList(int page, int limit, @RequestParam Map<String, String> paramMap){
        try {
            paramMap.put("username", SecurityUtils.getSubject().getSession().getAttribute("username").toString());
        } catch (Exception e) {
            // 平台用户点击
            paramMap.put("username", "platform");
        }

        if (paramMap.containsKey("shengfen")) {
            paramMap.remove("shengfen1");
        } else {
            paramMap.put("shengfen", paramMap.remove("shengfen1"));
        }
        if (paramMap.containsKey("field")) {
            paramMap.remove("field1");
        } else {
            paramMap.put("field", paramMap.remove("field1"));
        }
        if (paramMap.containsKey("order")) {
            paramMap.remove("order1");
        } else {
            paramMap.put("order", paramMap.remove("order1"));
        }
        if (paramMap.containsKey("rank")) {
            paramMap.remove("rank1");
        } else {
            paramMap.put("rank", paramMap.remove("rank1"));
        }

        int i = 0;
        Iterator<Map.Entry<String, String>> it = paramMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, String> entry = it.next();
            if(entry.getValue().equals("null")){
                it.remove();//使用迭代器的remove()方法删除元素
                i++;
            }
        }
        if(i!=0){
            paramMap.remove("yuefen1");
        }
        else if(paramMap.containsKey("yuefen")){paramMap.remove("yuefen1");}
        else{paramMap.put("yuefen", paramMap.remove("yuefen1"));}
        System.out.println(paramMap);
        PageHelper.startPage(page, limit);
        List<Orgmonth> list1 = evaluateService.getOrgList(paramMap);
        PageInfo<Orgmonth> pageInfo  = new PageInfo<>(list1);
        return new TableResponse(0,"查询成功", pageInfo.getList(),pageInfo.getTotal());
    }

    @PostMapping("/orgListCollected")
    @ResponseBody
    public Object orgListCollected(int page, int limit, @RequestParam Map<String, String> paramMap){
        try {
            paramMap.put("username", SecurityUtils.getSubject().getSession().getAttribute("username").toString());
        } catch (Exception e) {
            paramMap.put("username", "platform");
        }
        PageHelper.startPage(page, limit);
        PageInfo<Orgmonth> pageInfo  = new PageInfo<>(evaluateService.getOrgListCollected(paramMap));
        return new TableResponse(0,"查询成功", pageInfo.getList(),pageInfo.getTotal());
    }

    // 获取orgmonth里的所有orgcode
    @PostMapping("/orgCodeList")
    @ResponseBody
    public String orgCodeList() {
        Map<String, Object> result = new HashMap<>();
        result.put("orgCodeList", evaluateService.getAllOrgCode());
        return JSONArray.toJSONString(result);
    }

    // 获取当前用户收藏的所有orgcode
    @PostMapping("/orgCodeListCollected")
    @ResponseBody
    public String orgCodeListCollected() {
        Map<String, Object> result = new HashMap<>();
        String username;
        try {
            username = SecurityUtils.getSubject().getSession().getAttribute("username").toString();
        } catch (Exception e) {
            username = "platform";
        }
        result.put("orgCodeListCollected", evaluateService.getCollectedOrgCode(username));
        return JSONArray.toJSONString(result);
    }

    @GetMapping("/overview")
    public String overview(){
        return "back/overview";
    }
    @PostMapping("/overview/gailan")
    @ResponseBody
    public Integer overviewGailan(HttpServletRequest request) throws ParseException {
        String type=request.getParameter("type");
        switch (type) {
            case "evaluate":
                return evaluateService.getEvaluateNum();

            case "wangdian":
                return evaluateService.getOrgNum();

        }
        return 0;
    }
    @PostMapping("/overview/map")
    @ResponseBody
    public List<Map<String,Object>> overviewMap(HttpServletRequest request) throws ParseException {
        List<String> provList=Arrays.asList("北京","天津","上海", "重庆", "河北", "河南", "云南", "辽宁",  "黑龙江",  "湖南",  "安徽",  "山东",
                "新疆",  "江苏",  "浙江",  "江西", "湖北",  "广西",  "甘肃",  "山西",  "内蒙古", "陕西", "吉林", "福建", "贵州", "广东",
                "青海", "西藏",  "四川", "宁夏","海南","台湾","香港","澳门", "南海诸岛");
        List<Map<String,Object>> resultList = new LinkedList<>();
        for (int i=0;i<provList.size();i++){
            String province=provList.get(i);
            Integer num=evaluateService.getOrgNumByProv(province);
            Map<String,Object> map=new HashMap<>();
            map.put("name",province);
            map.put("selected","false");
            map.put("value",num);
            resultList.add(map);
        }

        return resultList;
    }

    public Map<String, String> calculateScore(Orgmonth orgmonth, String yuefen) {
        Map<String, Object> map = new HashMap<>();
        getMinMaxAndWeight(map, yuefen);
        Map<String, String> data = new HashMap<>();
        DecimalFormat df = new DecimalFormat("#.00");
        // 派送时效得分
        double score_age = (1/orgmonth.getAverageAge() - 1/(Double)map.get("max_averageAge")) /
                (1/(Double)map.get("min_averageAge") - 1/(Double)map.get("max_averageAge")) * 100;
        // 最大派送能力得分
        double score_maxCount = (orgmonth.getDailyMaxWaybillCount() - (Double)map.get("min_dailyMaxWaybillCount")) /
                ((Double)map.get("max_dailyMaxWaybillCount") - (Double)map.get("min_dailyMaxWaybillCount")) * 100;
        // 当日派件率得分
        double score_24hRate = (orgmonth.getAvgDeliveryCountRate() - (Double)map.get("min_avgDeliveryCountRate")) /
                ((Double)map.get("max_avgDeliveryCountRate") - (Double)map.get("min_avgDeliveryCountRate")) * 100;
        // 劳动生产率得分
        double score_labor = (orgmonth.getLaborProductivity() - (Double)map.get("min_laborProductivity")) /
                ((Double)map.get("max_laborProductivity") - (Double)map.get("min_laborProductivity")) * 100;
        // 人员利用率得分
        double score_deliveryRate = (orgmonth.getDeliveryRate() - (Double)map.get("min_deliveryRate")) /
                ((Double)map.get("max_deliveryRate") - (Double)map.get("min_deliveryRate")) * 100;
        // 工作负荷得分
        double score_workload;
        if (orgmonth.getWorkload() < 100) {
            score_workload = (orgmonth.getWorkload() - (Double) map.get("min_workload")) / (100 - (Double) map.get("min_workload")) * 100;
        } else {
            score_workload = ((Double) map.get("max_workload") - orgmonth.getWorkload()) / ((Double) map.get("max_workload") - 100) * 100;
        }

        data.put("orgCode", orgmonth.getOrgCode());
        data.put("yuefen", yuefen);
        data.put("score", df.format(orgmonth.getShangquanf()));
        data.put("score_age", df.format(score_age));
        data.put("score_maxCount", df.format(score_maxCount));
        data.put("score_24hRate", df.format(score_24hRate));
        data.put("score_labor", df.format(score_labor));
        data.put("score_deliveryRate", df.format(score_deliveryRate));
        data.put("score_workload", df.format(score_workload));
        data.put("type", orgmonth.getType());
        data.put("rank",orgmonth.getRank());
        data.put("size_rank",orgmonth.getRank3());
        data.put("dynamic_eff",df.format(orgmonth.getDynamicEff()));
        data.put("inc_coef",df.format(orgmonth.getIncCoef()));

        return data;
    }

    public Map<String, String> calculateScore1(Orgmonth orgmonth, String yuefen) {
        Map<String, Object> map = new HashMap<>();
        getMinMaxAndWeight(map, yuefen);
        Map<String, String> data = new HashMap<>();
        DecimalFormat df = new DecimalFormat("#.00");
        // 派送时效得分
        double score_age = (1/orgmonth.getAverageAge() - 1/(Double)map.get("max_averageAge")) /
                (1/(Double)map.get("min_averageAge") - 1/(Double)map.get("max_averageAge")) * 100;
        // 最大派送能力得分
        double score_maxCount = (orgmonth.getDailyMaxWaybillCount() - (Double)map.get("min_dailyMaxWaybillCount")) /
                ((Double)map.get("max_dailyMaxWaybillCount") - (Double)map.get("min_dailyMaxWaybillCount")) * 100;
        // 当日派件率得分
        double score_24hRate = (orgmonth.getAvgDeliveryCountRate() - (Double)map.get("min_avgDeliveryCountRate")) /
                ((Double)map.get("max_avgDeliveryCountRate") - (Double)map.get("min_avgDeliveryCountRate")) * 100;
        // 劳动生产率得分
        double score_labor = (orgmonth.getLaborProductivity() - (Double)map.get("min_laborProductivity")) /
                ((Double)map.get("max_laborProductivity") - (Double)map.get("min_laborProductivity")) * 100;
        // 人员利用率得分
        double score_deliveryRate = (orgmonth.getDeliveryRate() - (Double)map.get("min_deliveryRate")) /
                ((Double)map.get("max_deliveryRate") - (Double)map.get("min_deliveryRate")) * 100;
        // 工作负荷得分
        double score_workload;
        if (orgmonth.getWorkload() < 100) {
            score_workload = (orgmonth.getWorkload() - (Double) map.get("min_workload")) / (100 - (Double) map.get("min_workload")) * 100;
        } else {
            score_workload = ((Double) map.get("max_workload") - orgmonth.getWorkload()) / ((Double) map.get("max_workload") - 100) * 100;
        }

        data.put("orgCode", orgmonth.getOrgCode());
        data.put("yuefen", yuefen);
        data.put("score", df.format(orgmonth.getShangquanf()));
        data.put("score_age", df.format(score_age));
        data.put("score_maxCount", df.format(score_maxCount));
        data.put("score_24hRate", df.format(score_24hRate));
        data.put("score_labor", df.format(score_labor));
        data.put("score_deliveryRate", df.format(score_deliveryRate));
        data.put("score_workload", df.format(score_workload));

        return data;
    }

    // 对外接口，返回详细信息
    @PostMapping(value = "/openapi/detail", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getDetail(String orgCode, String yuefen, String key){
        Map<String, String> result = new HashMap<>();

        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(yuefen == null || yuefen.equals("") || orgCode == null || orgCode.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }

        Orgmonth orgmonth = evaluateService.getByNameAndYuefen(orgCode, yuefen);
        if (orgmonth == null) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }
        // 排名情况
        int[] nums = evaluateService.getOrgNumOfType(yuefen);
        int numOfType;
        String type = orgmonth.getType();
        switch (type) {
            case "小规模":
                numOfType = nums[1];
                break;
            case "中规模":
                numOfType = nums[2];
                break;
            case "大规模":
                numOfType = nums[3];
                break;
            default:
                numOfType = nums[4];
                break;
        }

        double loadscore_yuzhi = evaluateService.getLoadScoreByYuefenAndLoadRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double staffscore_yuzhi = evaluateService.getStaffScoreByYuefenAndStaffRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double agescore_yuzhi = evaluateService.getAgeScoreByYuefenAndAgeRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double laborscore_yuzhi = evaluateService.getLaborScoreByYuefenAndLaborRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double dailyscore_yuzhi = evaluateService.getDailyScoreByYuefenAndDailyRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);
        double maxscore_yuzhi = evaluateService.getMaxScoreByYuefenAndMaxRankAndType((int)Math.floor(numOfType*0.6),yuefen,type);

        DecimalFormat df = new DecimalFormat("#.00");

        //工作负荷
        String load_status;
        if(orgmonth.getLoadScore()>=loadscore_yuzhi)
            load_status = "良好";
        else load_status = "较差";

        //人员利用率
        String staff_status;
        if(orgmonth.getStaffScore()>=staffscore_yuzhi)
            staff_status = "良好";
        else staff_status = "较差";

        //派送时效
        String age_status;
        if(orgmonth.getAgeScore()>=agescore_yuzhi)
            age_status = "良好";
        else age_status = "较差";

        //劳动生产率
        String labor_status;
        if(orgmonth.getLaborScore()>=laborscore_yuzhi)
            labor_status = "良好";
        else labor_status = "较差";

        //当日派件率
        String daily_status;
        if(orgmonth.getDailyScore()>=dailyscore_yuzhi)
            daily_status = "良好";
        else daily_status = "较差";

        //最大派送能力
        String max_status;
        if(orgmonth.getMaxScore()>=maxscore_yuzhi)
            max_status = "良好";
        else max_status = "较差";

        result.put("code", "0");
        result.put("message", "success");

        result.put("load_score",df.format(orgmonth.getLoadScore()));
        result.put("load_rank",df.format(100-100.0*orgmonth.getLoadRank()/numOfType));
        result.put("load_status",load_status);
        result.put("load_thresh",df.format(loadscore_yuzhi));

        result.put("staff_score",df.format(orgmonth.getStaffScore()));
        result.put("staff_rank",df.format(100-100.0*orgmonth.getStaffRank()/numOfType));
        result.put("staff_status",staff_status);
        result.put("staff_thresh",df.format(staffscore_yuzhi));

        result.put("age_score",df.format(orgmonth.getAgeScore()));
        result.put("age_rank",df.format(100-100.0*orgmonth.getAgeRank()/numOfType));
        result.put("age_status",age_status);
        result.put("age_thresh",df.format(agescore_yuzhi));

        result.put("labor_score",df.format(orgmonth.getLaborScore()));
        result.put("labor_rank",df.format(100-100.0*orgmonth.getLaborRank()/numOfType));
        result.put("labor_status",labor_status);
        result.put("labor_thresh",df.format(laborscore_yuzhi));

        result.put("daily_score",df.format(orgmonth.getDailyScore()));
        result.put("daily_rank",df.format(100-100.0*orgmonth.getDailyRank()/numOfType));
        result.put("daily_status",daily_status);
        result.put("daily_thresh",df.format(dailyscore_yuzhi));

        result.put("max_score",df.format(orgmonth.getMaxScore()));
        result.put("max_rank",df.format(100-100.0*orgmonth.getMaxRank()/numOfType));
        result.put("max_status",max_status);
        result.put("max_thresh",df.format(maxscore_yuzhi));

        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回六项指标得分和总得分
    @PostMapping(value = "/openapi/orgScore", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String orgScore(String orgCode, String yuefen, String key) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(orgCode == null || yuefen == null || orgCode.equals("") || yuefen.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }
        Orgmonth orgmonth = evaluateService.getByNameAndYuefen(orgCode, yuefen);
        if (orgmonth == null) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }
        Map<String, String> data = calculateScore(orgmonth, yuefen);

        result.put("code", "0");
        result.put("message", "success");
        result.put("data", JSONArray.toJSONString(data));
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回当月最优网点的六项指标得分和总得分
    @PostMapping(value = "/openapi/bestOrg", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String bestOrg(String yuefen, String key) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(yuefen == null || yuefen.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }
        Orgmonth orgmonth = evaluateService.getMaxShangquanf(yuefen);
        if (orgmonth == null) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }
        Map<String, String> data = calculateScore(orgmonth, yuefen);

        result.put("code", "0");
        result.put("message", "success");
        result.put("data", JSONArray.toJSONString(data));
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回网点最近六个月的熵权分与平均值
    @PostMapping(value = "/openapi/historyScore",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String historyScore(String orgCode, String key, String yuefenBgn, String yuefenEnd) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(orgCode == null || orgCode.equals("") || yuefenBgn == null || yuefenBgn.equals("") || yuefenEnd == null || yuefenEnd.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }

//        // 最近六个月
//        DateFormat df = new SimpleDateFormat("yyyy-MM");
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//        String yuefenEnd = df.format(calendar.getTime());
//        calendar.add(Calendar.MONTH, -5);
//        String yuefenBgn = df.format(calendar.getTime());
        Map<String, Object> map = evaluateService.getShangquanfByNameAndYuefenRange(orgCode, yuefenBgn, yuefenEnd);
        if (map.get("res").equals("fail")) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }
        List<Double> scoreList = (List<Double>)map.get("shangquanf");
        double sum = 0;
        for (Double score : scoreList) {
            sum += score;
        }
        result.put("code", "0");
        result.put("message", "success");
        result.put("yuefenList",JSONArray.toJSONString(map.get("yuefen")));
        result.put("scoreList", JSONArray.toJSONString(scoreList));
        result.put("avgScore", new DecimalFormat("#.0000").format(sum / scoreList.size()));
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回当月最优网点的六项指标得分和总得分
    @PostMapping(value = "/openapi/dailyIndex",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String dailyIndex(String orgCode, String key, String indexType, String dateBgn, String dateEnd) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(orgCode == null || orgCode.equals("") || dateBgn == null || dateBgn.equals("")
                || dateEnd == null || dateEnd.equals("") || indexType == null || indexType.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }
        Map<String,Object> res;
        switch (indexType) {
            case "workload": // 工作负荷
                res = evaluateService.getWorkLengthByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Double>) res.get("worklength")).toArray(new Double[0]));
                }
                break;
            case "shixiao":
                res = evaluateService.getShixiaoByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Double>) res.get("Shixiao")).toArray(new Double[0]));
                }
                break;
            case "shengchanlv":
                res = evaluateService.getShengchanlvByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Double>) res.get("shengchanlv")).toArray(new Double[0]));
                }
                break;
            case "deliveryCount": //人员利用率
                res = evaluateService.getDeliveryCountByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Integer>) res.get("deliveryCount")).toArray(new Integer[0]));
                }
                break;
            case "deliveryCountOfDay": // 当日派件量
                res = evaluateService.getDeliveryCountOfDayByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Integer>) res.get("deliveryCountOfDay")).toArray(new Integer[0]));
                }
                break;
            case "deliveryCountRate":  // 当日派件率
                res = evaluateService.getDeliveryCountRateByNameAndDateRange(orgCode, dateBgn, dateEnd);
                if (!res.get("res").equals("fail")) {
                    res.put("data", ((List<Double>) res.get("deliveryCountRate")).toArray(new Double[0]));
                }
                break;
            default:
                result.put("code", "4004");
                result.put("message", "indexType error!");
                return JSONArray.toJSONString(result);
        }
        if (res.get("res").equals("fail")) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }

        result.put("code", "0");
        result.put("message", "success");
        List<String> dateList = (List<String>) res.get("date");
        result.put("dateList", JSONArray.toJSONString(dateList.toArray(new String[0])));
        result.put("dataList", JSONArray.toJSONString(res.get("data")));
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回网点列表
    @PostMapping(value = "/openapi/orgList",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String bestOrg(String key, Integer page, Integer limit, @RequestParam Map<String, String> paramMap) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(page == null || page < 0 || limit == null || limit <= 0 ) {
            result.put("code", "4002");
            result.put("message", "请求参数不正确！");
            return JSONArray.toJSONString(result);
        }

        PageHelper.startPage(page, limit);
        List<Orgmonth> list1 = evaluateService.getOrgList(paramMap);
        PageInfo<Orgmonth> pageInfo  = new PageInfo<>(list1);
        if (pageInfo.getTotal() == 0) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }

        // 转换为json时只显示部分列
        String[] includeProperties = {"orgCode", "yuefen", "shengfen", "shangquanf", "rank", "averageAge",
                "avgDeliveryCountRate", "laborProductivity", "dailyMaxWaybillCount", "deliveryRate", "workload",
                "ageScore","dailyScore","maxScore","laborScore","staffScore","loadScore"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter();
        includefilter.addIncludes(includeProperties);

        result.put("code", "0");
        result.put("message", "success");
        result.put("data", JSONArray.toJSONString(pageInfo.getList(), includefilter));
        result.put("page", "" + page);
        result.put("limit", "" + limit);
        result.put("total", "" + pageInfo.getTotal());
        result.put("pages", "" + (int)Math.ceil(1.0 * pageInfo.getTotal() / limit));
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回评分推算值
    @PostMapping(value = "/openapi/predict",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String predict(String key, String yuefen, String orgCode,  Double age, Integer maxCount,
                          Double dailyRate, Double labor, Double deliveryRate, Double workload) {
        Map<String,String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(yuefen == null || yuefen.equals("") || orgCode == null || orgCode.equals("") || age == null
                || maxCount == null || dailyRate == null || labor == null || deliveryRate == null || workload == null) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }
        Orgmonth orgmonth = new Orgmonth();
        orgmonth.setYuefen(yuefen);
        orgmonth.setOrgCode(orgCode);
        orgmonth.setAverageAge(age);
        orgmonth.setDailyMaxWaybillCount(maxCount);
        orgmonth.setAvgDeliveryCountRate(dailyRate);
        orgmonth.setLaborProductivity(labor);
        orgmonth.setDeliveryRate(deliveryRate);
        orgmonth.setWorkload(workload);
        orgmonth.setShangquanf(0.0);

        Map<String, String> data = calculateScore1(orgmonth, yuefen);

        // 计算熵权法得分
        Weight w = evaluateService.getByYuefen(yuefen);
        double score = w.getAverageage() * Double.parseDouble(data.get("score_age"))
                + w.getDeliveryrate() * Double.parseDouble(data.get("score_deliveryRate"))
                + w.getWorkload() * Double.parseDouble(data.get("score_workload"))
                + w.getAvgdeliverycountrate() * Double.parseDouble(data.get("score_24hRate"))
                + w.getDailymaxwaybillcount() * Double.parseDouble(data.get("score_maxCount"))
                + w.getWaybillnocount() * Double.parseDouble(data.get("score_labor"));
        data.put("score", String.format("%.2f",score));

        result.put("code", "0");
        result.put("message", "success");
        result.put("data", JSONArray.toJSONString(data));
        return JSONArray.toJSONString(result);
    }


    // 对外接口，返回各项权重
    @PostMapping(value="/openapi/weight",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getWeight(String key, String yuefen){
        Map<String, String> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(yuefen == null || yuefen.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }

        Weight w = evaluateService.getByYuefen(yuefen);
        if (w == null) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }

        java.text.DecimalFormat df =new java.text.DecimalFormat("#.0000");

        result.put("W_dailyMaxWaybillCount",df.format(w.getDailymaxwaybillcount()));
        result.put("W_averageAge",df.format(w.getAverageage()));
        result.put("W_waybillNoCount",df.format(w.getWaybillnocount()));
        result.put("W_avgDeliveryCountRate",df.format(w.getAvgdeliverycountrate()));
        result.put("W_deliveryRate", df.format(w.getDeliveryrate()));
        result.put("W_workload", df.format(w.getWorkload()));

        result.put("code", "0");
        result.put("message", "success");
        return JSONArray.toJSONString(result);
    }

    // 对外接口，返回经营建议
    @PostMapping(value="/openapi/advice",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getAdvice(String key, String orgCode, String yuefen) {
        Map<String, Object> result = new HashMap<>();
        if (key == null || !key.equals(APIKEY)) {
            result.put("code", "4001");
            result.put("message", "key验证失败！");
            return JSONArray.toJSONString(result);
        }
        if(yuefen == null || yuefen.equals("") || orgCode == null || orgCode.equals("")) {
            result.put("code", "4002");
            result.put("message", "请求参数不完整！");
            return JSONArray.toJSONString(result);
        }
        Orgmonth orgmonth = evaluateService.getByNameAndYuefen(orgCode, yuefen);
        if (orgmonth == null) {
            result.put("code", "4003");
            result.put("message", "没有找到相关记录！");
            return JSONArray.toJSONString(result);
        }
        // 排名情况
        int[] nums = evaluateService.getOrgNumOfType(yuefen);
        int total = nums[0], numOfType;
        String type = orgmonth.getType();
        switch (type) {
            case "小规模":
                numOfType = nums[1];
                break;
            case "中规模":
                numOfType = nums[2];
                break;
            case "大规模":
                numOfType = nums[3];
                break;
            default:
                numOfType = nums[4];
                break;
        }

        java.text.DecimalFormat df =new java.text.DecimalFormat("#.00");
        result.put("effi_score",df.format(orgmonth.getShangquanf()));
        result.put("total_pct",df.format(100-100.0*orgmonth.getRank1()/total));
        result.put("total_num",orgmonth.getRank1());
        result.put("month_volume",orgmonth.getDeliveryCountMonth());
        result.put("size",orgmonth.getType());
        result.put("same_size_pct",df.format(100-100.0*orgmonth.getRank2()/numOfType));
        result.put("same_size_rank",orgmonth.getRank2());


//        Map<String, Object> rank = new HashMap<>();
        result.put("effi_score",df.format(orgmonth.getShangquanf()));
        result.put("total_pct",df.format(100-100.0*orgmonth.getRank1()/total));
        result.put("total_num",orgmonth.getRank1());
        result.put("month_volume",orgmonth.getDeliveryCountMonth());
        result.put("size",orgmonth.getType());
        result.put("same_size_pct",df.format(100-100.0*orgmonth.getRank2()/numOfType));
        result.put("same_size_rank",orgmonth.getRank2());

//        String rank = String.format("当前网点效率分数在为%.2f,超过%.2f%%的网点,排名%d; 本月业务量为%d, 属于%s网点,超过%.2f%%的同类网点,排名%d。",
//                orgmonth.getShangquanf(), 100-100.0*orgmonth.getRank1()/total, orgmonth.getRank1(),
//                orgmonth.getDeliveryCountMonth(), orgmonth.getType(), 100-100.0*orgmonth.getRank2()/numOfType,orgmonth.getRank2());
        // 较差指标
        List<String> weakIndex = new ArrayList<>();
        if (1.0 * orgmonth.getAgeRank() / numOfType > 0.6) {
            weakIndex.add("派送时效");
        }
        if (1.0 * orgmonth.getDailyRank() / numOfType > 0.6) {
            weakIndex.add("当日派件率");
        }
        if (1.0 * orgmonth.getLaborRank() / numOfType > 0.6) {
            weakIndex.add("劳动生产率");
        }
        if (1.0 * orgmonth.getMaxRank() / numOfType > 0.6) {
            weakIndex.add("最大派送能力");
        }
        if (1.0 * orgmonth.getStaffRank() / numOfType > 0.6) {
            weakIndex.add("人员利用率");
        }
        if (1.0 * orgmonth.getLoadRank() / numOfType > 0.6) {
            weakIndex.add("工作负荷");
        }
        int n = weakIndex.size();
        if (n > 0) {
            StringBuilder weak = new StringBuilder();
            for (int i = 0; i < n; ++i) {
                weak.append(weakIndex.get(i));
                if (i != n-1) {
                    weak.append("\n");
                }
            }
            result.put("weak", weak.toString());

            // 改进建议
            // TODO: 后续改为在数据库里查
            Map<String, String> advices = new HashMap<>();
            advices.put("派送时效", "平均时效：网点当前平均派送时效较长，可以通过使用智能快递柜、启用代收点、驿站等方式缩短时效。");
            advices.put("当日派件率", "当日签收率：网点当前当日签收率较低，可以通过合理安排下车、派送时间，合理使用快递柜、驿站等方式提高当日签收率。");
            advices.put("劳动生产率", "劳动生产率：网点当前劳动生产率较低，可以通过与其他网点进行资源共享、重新规划区域等方式提高劳动生产率。");
            advices.put("最大派送能力", "最大派送能力：网点当前最大派送能力较低，可以通过与其他网点资源共享提升最大派送能力。");
            advices.put("人员利用率", "人员利用率：网点当前人员利用率较低，应尽量提升人员稳定性，减少人员流失。");
            advices.put("工作负荷", "工作负荷：网点当前人员工作负荷较高，可以通过增加快递员数量、重新规划区域等方式降低快递员工作负荷。");

            StringBuilder advice = new StringBuilder();
            for (int i = 0; i < n; ++i) {
                advice.append(advices.get(weakIndex.get(i)));
                if (i != n-1) {
                    advice.append("\n");
                }
            }
            result.put("advice", advice.toString());
        } else {
            result.put("advice", "当前各项指标表现良好，请继续努力！");
        }

        result.put("code", "0");
        result.put("message", "success");
        return JSONArray.toJSONString(result);
    }
}
